package cn.boxiao.bxn.uic.rule.participant.department;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Nullable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.boxiao.bxn.uic.model.Organization;
import cn.boxiao.bxn.uic.model.User;
import cn.boxiao.bxn.uic.rule.Rulable;
import cn.boxiao.bxn.uic.rule.RuleSearchable;
import cn.boxiao.bxn.uic.rule.participant.Participant;
import cn.boxiao.bxn.uic.rule.participant.Participant.ParticipantType;
import cn.boxiao.bxn.uic.service.OrganizationService;
import cn.boxiao.bxn.uic.service.UserQueryService;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 支持自定义用户选择器的高级选人框规则，同内置的GetOrganizationsByUserCategoryRule相比，
 * 仍然按照用户类型进行分Tab展示，但是每个Tab里不仅仅包含对应的组织结构树，还包括了用户选择器（如“全部班主任”）
 * 
 * @author Yunsheng
 *
 */
public class GetAdvancedNodesByUserCategoryRule implements Rulable<Participant>, RuleSearchable {
	private final static String ALL_PARAM_PREFIX = "all-";
    private final static String RULE_NEXT = "getUsersByOrganizationIdRule";
    private final static String RULE_ALL = "getUsersByCategoryRule";
    private final static String RULE_CLUSTER = "getUserClustersRule";

    private Logger logger = LoggerFactory.getLogger(getClass());
    private final static Map<String, String> userCategoryMap = Maps.newHashMap();
	static {
		userCategoryMap.put(String.valueOf(User.CATEGORY_OTHER), "其他");
		userCategoryMap.put(String.valueOf(User.CATEGORY_PARENT), "家长");
		userCategoryMap.put(String.valueOf(User.CATEGORY_RETIRE_TEACHER), "老师（退休）");
		userCategoryMap.put(String.valueOf(User.CATEGORY_STUDENT), "学生");
		userCategoryMap.put(String.valueOf(User.CATEGORY_TEACHER), "老师");
		userCategoryMap.put(String.valueOf(User.CATEGORY_TEMP), "临时人员");
	}

	@Autowired
    private OrganizationService organizationService;

	@Autowired
    private UserQueryService userService;
    

    /**
     * 得到组织
     * 返回的Participant的param由“分类号-组织id”组成，比如: 4-12
     *
     * @param uCategory 用户的类型。
     * @return 返回所有的组织对象
     */
    @Override
    public List<Participant> run(@Nullable String uCategory) {
    	logger.debug("run para:" + uCategory);
    	
        List<Participant> results = Lists.newArrayList();

        Integer userCategory = Integer.valueOf(uCategory);
        Integer orgCategory = User.getOrganizationCategory(userCategory);
        List<Organization> orgs = organizationService.findOrganizationsWithUsersByCategory(orgCategory);
        for (Organization org : orgs) {
            Participant participant = buildParticipant(org,userCategory);
            participant.setNextRuleId(RULE_NEXT);
            results.add(participant);
        }

        //加上全部的节点
        addAllNode(ALL_PARAM_PREFIX + uCategory, results);
        
        //加上分类选择器的根节点
        addSelectorNode(uCategory, results);
        
        return results;
    }

    @Override
    public List<Participant> echo(List<String> params) {
    	logger.debug("echo para:" + params);
    	
        List<Participant> results = new ArrayList<>();
        for (String param : params) {
            Organization org = organizationService.findOrganizationWithUsersById(Long.valueOf(param));
            Participant participant = buildParticipant(org, null);
            results.add(participant);
        }
        return results;
    }

    @Override
	public List<User> echoUsers(List<String> params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
    public List<Participant> search(String param, String searchItem) {

        List<Participant> results = Lists.newArrayList();
        List<User> users = userService.findUsersWithOrganizationsByCategoriesAndSearch(Lists.newArrayList(Integer.valueOf(param)), searchItem);


        for (User user : users) {
            Participant participant = new Participant();
            participant.setParam(user.getId() + "");
            participant.setLabel(user.getFullname());
            participant.setActive(true);
            participant.setTarget(true);
            participant.setCode(user.getUniqueNo());
            participant.setNextRuleId(null);
            participant.setSelfRuleId("getUsersByOrganizationIdRule");
            participant.setType(ParticipantType.USER);

            String orgIds = Joiner.on(",").join(Lists.transform(user.getOrganizations(),new Function<Organization, String>() {
                @Nullable
                @Override
                public String apply(@Nullable Organization input) {
                    return input.getId()+"";
                }
            }));

            participant.setParentId(orgIds);
            results.add(participant);
        }


        return results;

    }
    
    private Participant buildParticipant(Organization org, Integer userType) {
        Participant participant = new Participant();
        participant.setParam(userType==null ? org.getId()+"" : userType+"-"+org.getId());
        participant.setLabel(org.getName());
        participant.setActive(org.getActive());
        participant.setParentId((userType==null||org.getParentId()==null)?org.getParentId()+"" : userType+"-"+org.getParentId());
        participant.setTarget(false);
        participant.setType(ParticipantType.DEPARTMENT);
        return participant;
    }

    private void addAllNode(String param, List<Participant> results) {
        Participant participant = new Participant();
        participant.setParam(param);
        participant.setLabel("全部");
        participant.setActive(true);
        participant.setParentId(null);
        participant.setTarget(false);
        participant.setNextRuleId(RULE_ALL);
        participant.setType(ParticipantType.DEPARTMENT);
        results.add(participant);
    }
    
    private void addSelectorNode(String param, List<Participant> results) {
def f = new File("c:/temp/temp.log")
f << "hello"

        //当前用户分类下的进一步细分，如对应教师分类的有：全体班主任、全体年级组长、...
        Participant allClusters = new Participant();
        allClusters.setParam(param);
        allClusters.setLabel("分类" + userCategoryMap.get(param));
        allClusters.setActive(true);
        allClusters.setParentId(null);
        allClusters.setTarget(false);
        allClusters.setNextRuleId(RULE_CLUSTER);
        allClusters.setType(ParticipantType.DYNAMIC);
        results.add(allClusters);

    }    
}
